package democache;

import democache.computer.Computable;
import democache.computer.MayFail;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Brook
 * 描述：出于安全性考虑，缓存需要设置有效期，到期自动失效，
 * 否则如果缓存一直不失效，那么带来缓存不一致问题
 */
public class DemoCache10<A, V> implements Computable<A, V> {

    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();

    private final Computable<A, V> c;

    public DemoCache10(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException {

        while (true) {
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> callable = new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<>(callable);

                f =cache.putIfAbsent(arg,ft);
                if(f == null){
                    f = ft;
                    System.out.println("从FutrureTasl调用了计算函数");
                    ft.run();
                }
            }
            try {
                return f.get();
            } catch(CancellationException e) {
                System.out.println("被取消了");
                cache.remove(arg);
                throw e;
            }catch (InterruptedException e) {
                cache.remove(arg);
                throw e;
            } catch (ExecutionException e) {
                System.out.println("计算错误，需要重试");
                cache.remove(arg);
            }
        }
    }

    //设置随机的缓存过期时间
    public V computeRandomExpire(A arg) throws InterruptedException {
        long randomExpire = (long) (Math.random() * 10000);
        return compute(arg, randomExpire);
    }

    //设置过期时间 start
    public final static ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

    public V compute(A arg, long expire) throws InterruptedException {
        if(expire>0) {
            executor.schedule(new Runnable() {
                @Override
                public void run() {
                    expire(arg);
                }
            }, expire, TimeUnit.MILLISECONDS);
        }
        return compute(arg);
    }

    public synchronized void expire(A key) {
        Future<V> future = cache.get(key);
        if (future != null) {
            if(!future.isDone()){
                System.out.println("Future任务被取消了");
                future.cancel(true);
            }
            System.out.println("过期时间到，缓存被清除");
            cache.remove(key);
        }
    }
    //设置过期时间 end





    public static void main(String[] args) throws Exception {
        DemoCache10<String, Integer> demoCache2 = new DemoCache10(new MayFail());

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.computeRandomExpire("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果：" + result);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.computeRandomExpire("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第二次计算结果：" + result);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.computeRandomExpire("667");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第三次计算结果：" + result);
            }
        }).start();

        Thread.sleep(6000L);
        Integer result = demoCache2.computeRandomExpire("666");
        System.out.println("第三次的计算结果：" + result);
    }
}
